package com.agrm.order.mapper;

import com.agrm.model.order.pojo.Order;
import com.agrm.model.order.search.OrderSearchBean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface OrderMapper extends BaseMapper<Order> {

    /**
     * 根据订单号查询订单
     * @param orderNo
     * @return
     */
    @Select("SELECT * FROM `order` WHERE order_no = #{orderNo}")
    Order selectByOrderNo(@Param("orderNo") String orderNo);


    /**
     * 逻辑删除订单
     * @param ids
     * @return
     */
    int logicDeleteByIds(@Param("ids") List<Integer> ids);

    default Page<Order> findAll(OrderSearchBean osb, Page<Order> page) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();

        // 基本条件查询
        wrapper.eq(osb.getId() != null, "id", osb.getId())
                .like(osb.getOrderNo() != null, "order_no", osb.getOrderNo())
//                .eq(osb.getMemberAccount() != null, "member_account", osb.getMemberAccount())
                .like(osb.getAlipayTradeNo() != null, "alipay_trade_no", osb.getAlipayTradeNo())
                .like(osb.getReceiverName() != null, "receiver_name", osb.getReceiverName())
                .like(osb.getReceiverPhone() != null, "receiver_phone", osb.getReceiverPhone())
                .like(osb.getReceiverAddrDetail() != null, "receiver_addr_detail", osb.getReceiverAddrDetail())
                .ge(osb.getOrderTimeStart() != null, "created_time", osb.getOrderTimeStart())
                .lt(osb.getOrderTimeEnd() != null, "created_time", osb.getOrderTimeEnd())
                .ge(osb.getTotalPayStart() != null, "total_pay", osb.getTotalPayStart())
                .lt(osb.getTotalPayEnd() != null, "total_pay", osb.getTotalPayEnd())
                .eq(osb.getIsDel() != null, "is_del", osb.getIsDel())
                .eq(osb.getStatus() != null, "status", osb.getStatus())
                .eq(osb.getPayType() != null, "pay_type", osb.getPayType());

        // 关键词搜索（多字段模糊查询）
        if (osb.getKeyword() != null && !osb.getKeyword().isEmpty()) {
            wrapper.and(w -> w.like("order_no", osb.getKeyword())
                    .or().like("receiver_name", osb.getKeyword())
                    .or().like("receiver_phone", osb.getKeyword())
                    .or().like("receiver_addr_detail", osb.getKeyword())
                    .or().like("order_comment", osb.getKeyword())
                    .or().like("description", osb.getKeyword()));
        }

        return selectPage(page, wrapper);
    }

    @Select("select * from `order` where seckill_no=#{seckillNo}")
    Order selectBySeckillNo(String seckillNo);
}
